<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ params.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="export2Excel"
          >导出</el-button>
          <!-- 放入权限标识  checkPermission()-->
          <el-button v-if="checkPermission('add-employee')" size="small" type="primary" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employessList">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="" label="姓名" sortable="">
            <template #default="{row}">
              <el-row class="staffPhoto">
                <img v-imgErr="require('@/assets/common/头像.jpg')" :src="row.staffPhoto" alt="" @click="showQrCode(row.staffPhoto)">
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatterEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="correctionTime" label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.correctionTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template #default="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="params.size"
            :total="params.total"
            :current-page="params.page"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 模态框 -->
      <!-- 新增员工模态框 -->
      <add-employee :show-dialog.sync="showDialog" @addEmployee="getEmployeesList" />
      <!-- 二维码模态框 -->
      <el-dialog title="二维码" :visible="showCodeDialog" @close="showCodeDialog=false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 分配角色 -->
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import { getEmployeesList, delEmployee } from '@/api/employees'
// 引入员工枚举信息
import employees from '@/api/constant/employees'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
export default {
  components: { addEmployee, assignRole },
  data() {
    return {
      params: {
        page: 1,
        size: 5,
        total: 0
      },
      employessList: [],
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 显示角色模态框
    async showRole(id) {
      await this.$refs.assignRole.getUserInfoById(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 显示二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },

    // 获取员工列表信息
    async getEmployeesList() {
      const { rows, total } = await getEmployeesList(this.params)
      this.params.total = total
      // 本地数据没有enableState这玩意 要在线接口才有 用本地接口的话加上这玩意
      this.employessList = rows.map(item => {
        return {
          ...item,
          enableState: item.enableState || 1
        }
      })
    },
    // 换页
    currentChange(val) {
      this.params.page = val
      this.getEmployeesList()
    },
    // 格式化聘用形式信息
    formatterEmployment(row, col, cell, index) {
      // employees 是员工枚举数据
      const obj = employees.hireType.find(item => Number(item.id) === Number(cell))
      // console.log(obj)
      return obj ? obj.value : '未知'
    },
    // 导出
    async export2Excel() {
      // 发请求获取所有数据
      const { rows } = await getEmployeesList({
        page: 1,
        size: this.params.total
      })
      // 表头字典
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      console.log(header)
      const data = rows.map(item => {
        return this.obj2arr(item, dict)
      })
      // 导出Excel的方法
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header,
        data
      })
    },
    // data数组数据对象转数组
    obj2arr(item, dict) {
      const newArr = []
      for (const key in dict) {
        const newKey = dict[key]
        const newVal = item[newKey]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          // 时间格式化
          newArr.push(formatDate(newVal))
        } else if (newKey === 'formOfEmployment') {
          // 聘用形式 枚举格式化
          const obj = employees.hireType.find(item => item.id === newVal)
          newArr.push(obj ? obj.value : '未知')
        } else {
          newArr.push(newVal)
        }
      }
      return newArr
    },
    // 删除打工仔
    async delEmployee(id) {
      await this.$confirm('真的要删除这位打工仔嘛？')
      await delEmployee(id)
      this.$message.success('操作成功')
      if (this.params.page > 1 && this.employessList.length === 1) {
        this.params.page--
      }
      this.getEmployeesList()
    },
    // 新增打工仔
    addEmployee() {
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto{
  height: 80px;
  display: flex;
  justify-content: center;
  img{
    width: 90%;
    object-fit: contain;
  }
}
</style>
